package sailhero

import (
	"encoding/json"
	"fmt"
	"github.com/shopspring/decimal"
	"github.com/wsw188440873/ctrl-cali/model"
	"github.com/wsw188440873/ctrl-cali/types"
	"strconv"
)

func ZeroDriftAndSpanDriftSubTask(modelId string, params map[string]interface{}) (map[string]float64, bool) {
	if _, ok := params["collect_data"]; !ok {
		return nil, false
	}
	if _, ok := types.Range[modelId]; !ok {
		return nil, false
	}
	dataMap, ok := params["collect_data"].(map[string][]float64)
	if ok == false {
		return nil, false
	}
	resp := make(map[string]float64)
	for k, values := range dataMap {
		key := k
		if k != "0" {
			number, _ := strconv.Atoi(k)
			// 待测分析仪器满量程值
			r := types.Range[modelId]
			key = decimal.NewFromFloat(float64(number) / r).Round(2).String()
		}
		switch key {
		case "0":
			resp["Z"] = values[0]
			break
		case "0.2":
			resp["M20"] = values[0]
			break
		case "0.8":
			resp["M80"] = values[0]
			break
		}
	}
	return resp, true
}

func ZeroDriftAndSpanDrift(pid string) (string, error) {
	taskLog, err := model.Dao.TTask.QuerySubTaskLog(pid)
	if err != nil {
		return "", err
	}
	params := make([]map[string]float64, 0, len(taskLog))
	for _, v := range taskLog {
		b, _ := v.Content.MarshalJSON()
		data := model.ContentJson{}
		_ = json.Unmarshal(b, &data)
		dataMap := data.CollectData
		if len(dataMap) == 0 {
			continue
		}
		temp := make(map[string]float64)
		for k, values := range dataMap {
			key := k
			if k != "0" {
				number, _ := strconv.Atoi(k)
				// 待测分析仪器满量程值
				r := types.Range[data.ModelId]
				key = decimal.NewFromFloat(float64(number) / r).Round(2).String()
			}
			switch key {
			case "0":
				temp["Z"] = values[0]
				break
			case "0.2":
				temp["M20"] = values[0]
				break
			case "0.8":
				temp["M80"] = values[0]
				break
			}
		}
		params = append(params, temp)
	}
	paramsLen := len(params)
	if paramsLen < 2 {
		return "", nil
	}

	ZD := params[paramsLen-1]["Z"] - params[paramsLen-2]["Z"]
	MSD := params[paramsLen-1]["M20"] - params[paramsLen-2]["M20"]
	USD := params[paramsLen-1]["M80"] - params[paramsLen-2]["M80"]

	return fmt.Sprintf("ZD=%v,MSD=%v,USD=%v", ZD, MSD, USD), nil
}
